#include "StdAfx.h"
#include <string>
#include <Util/StringUtil.h>
#include <interface/data_op/table_wrapper.h>
#include "white_name_op.h"

namespace aot{ namespace data{

white_name_op_impl::white_name_op_impl(void)
{
}

white_name_op_impl::~white_name_op_impl(void)
{
}

bool
white_name_op_impl::insert(const char* buddy_id)
{
    if ( !g_db_user ) return false;

    if ( this->find(buddy_id) )
    {
        return false;
    }
    std::string str_buddy_id = buddy_id;
    remove_sin_quot(str_buddy_id);

    std::string sql_fmt = 
        "insert into file_white_nums \
        (user_id) \
        values\
        ('%s');";

    std::string sql_exe;
    sql_exe = aot::tt::utility::StrUtil::Printf(sql_fmt.c_str(), str_buddy_id.c_str());

    return g_db_user->exec(sql_exe.c_str());
}

bool
white_name_op_impl::del(const char* buddy_id)
{
    std::string str_buddy_id = buddy_id;
    remove_sin_quot(str_buddy_id);

    std::string sql_fmt;
    std::string sql_exe;
    
    sql_fmt = "delete from file_white_nums where user_id='%s';";
    sql_exe = aot::tt::utility::StrUtil::Printf(sql_fmt.c_str(), str_buddy_id.c_str());
    return g_db_user->exec(sql_exe.c_str());
}

bool
white_name_op_impl::find(const char* buddy_id)
{
    std::string str_buddy_id = buddy_id;
    remove_sin_quot(str_buddy_id);
    int total;
    std::string sql_fmt = "select count(*) as t from file_white_nums where user_id='%s';";
    std::string sql_exe = aot::tt::utility::StrUtil::Printf(sql_fmt.c_str(), str_buddy_id.c_str());
    total = g_db_user->exec_scalar(sql_exe.c_str());
    return ( total > 0 );
}

bool
white_name_op_impl::get_white_names(aot::tt::ivec_str** out)
{
    aot::tt::vec_str_impl* p = new aot::tt::vec_str_impl;
    *out = p;

    std::string sql_exe;
    sql_exe = "select user_id from file_white_nums;";
    aot::data::table_helper t_table;

    bool ret = g_db_user->exec_and_get_record(sql_exe.c_str(), t_table);

    std::string value;
    for( int i = 0; i < t_table.get_rows_count(); i++ )
    {
        t_table.set_row_index(i);

        value = t_table.get_field_value_str("user_id");
        p->impl().push_back(value);
    }

    return ret;
}

bool
white_name_op_impl::update_white_names(aot::tt::ivec_str* p)
{
    if ( p->size() == 0 )
    {
        return false;
    }

    this->begin_transaction();

    g_db_user->exec("delete from file_white_nums;");

    for( p->goto_begin(); !p->is_end(); p->goto_next() )
    {
        this->insert(p->get_value());
    }

    return this->commit_transaction();
}


}} /* end namespace aot/data*/
